package com.result.demo.global.filterLists;

import com.alibaba.fastjson.JSONObject;
import com.result.demo.global.config.GlobalConfig;
import com.result.demo.global.enums.ResultCode;
import com.result.demo.global.sign.BodyReaderHttpServletRequestWrapper;
import com.result.demo.global.sign.BodyRequestWrapper;
import com.result.demo.global.sign.HttpUtils;
import com.result.demo.global.sign.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.http.HttpMethod;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * @ProjectName: project
 * @Package: com.base.project.filters.filterLists
 * @Description: java类作用描述
 * @Author: Z.G.C
 * @CreateDate: 2020/5/15 4:10 PM
 * @UpdateUser: Z.G.C
 * @UpdateDate: 2020/5/15 4:10 PM
 * @UpdateRemark: The modified content
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2020</p>
 */
@Slf4j
public class SignAuthFilter implements Filter{
    private WebApplicationContext wac;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        wac = (WebApplicationContext) filterConfig.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {


    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;


    //解决跨域的问题

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With, Food-App-Id, User-Token");
        response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");


    String method = request.getMethod();
        System.out.println(method);
        // 防止options 请求
        if ((HttpMethod.OPTIONS).equals(request.getMethod())) {
        response.setStatus(HttpStatus.SC_NO_CONTENT);
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With, Food-App-Id, User-Token");
        response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        response.setHeader("Access-Control-Max-Age", "1");
        chain.doFilter(request, response);
        return;
    }

    // 初始化 officeCode
//    Map<String, String[]> initMap = initOfficeCode(request, response);
//        if(initMap.get("officeCode") != null ){
        // 将officeCode 添加进 请求流数据中
//        HttpServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(request, initMap);
        HttpServletRequest requestWrapper = new BodyRequestWrapper(request);
        // 白名单
//        if (verfilyUrl(request.getRequestURI())) {
//            chain.doFilter(requestWrapper, response);
//            return;
//        }
//        // 验签校验
//        if (!GlobalConfig.getSignCheck()) {
//            chain.doFilter(requestWrapper, response);
//            return;
//        }
        //获取全部参数(包括URL和body上的)
        SortedMap<String, Object> allParams = HttpUtils.getAllParams(requestWrapper);
        if (SignUtil.verifySign(allParams)) {
            chain.doFilter(requestWrapper, response);
        } else {
            initResponse(response, ResultCode.INVALID_SIGN);
        }
//    }
}

    private Map<String, String[]> initOfficeCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        Map<String, String[]> initMap = new HashMap<String, String[]>(request.getParameterMap());
            initMap.put("officeCode", new String[]{"123"});
        return initMap;
    }

    private boolean accessControlAllowOrigin(String origin) {
        List<String> originList = new ArrayList<>();
        originList.add("http://localhost:8080");
        if (originList.contains(origin)) {
            return true;
        }
        return false;
    }

    @Override
    public void destroy() {

    }


    private boolean verfilyUrl(String url) {
        List<String> list = new ArrayList<String>();

        if (list.contains(url)) {
            return true;
        }
        return false;


    }

    private void initResponse(HttpServletResponse response, ResultCode resultCode) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", resultCode.getCode());
        jsonObject.put("message", resultCode.getMessage());
        jsonObject.put("data", null);
        writer.write(jsonObject.toString());

        return;
    }
}
